package com.lanchetech.admin.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.lanchetech.admin.service.ActivityService;
import com.lanchetech.bean.request.ActivityReq;
import com.lanchetech.bean.response.BasePageResp;
import com.lanchetech.bean.response.BaseResp;
import com.lanchetech.bean.response.ResultData;
import com.lanchetech.bean.response.SpuResp;
import com.lanchetech.bean.util.PageHelpUtil;
import com.lanchetech.bean.vo.ActivityVo;
import com.lanchetech.bean.vo.SkuItemVO;
import com.lanchetech.common.constants.BaseConstant;
import com.lanchetech.common.enums.ActivityEnum;
import com.lanchetech.common.enums.ResultCode;
import com.lanchetech.dao.*;
import com.lanchetech.entity.*;
import com.lanchetech.service.DaoService;
import jodd.util.StringUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.*;
import java.util.stream.Collectors;

@Service
public class ActivityServiceImpl extends ServiceImpl<ActivityMapper, Activity> implements ActivityService {

    @Resource
    private ActivityBindSpuMapper bindSpuMapper;
    @Resource
    private SpuMapper spuMapper;
    @Resource
    private SkuMapper skuMapper;
    @Resource
    private ShopMapper shopMapper;
    @Resource
    private ActivityMapper activityMapper;


    @Override
    public ResultData<BasePageResp<ActivityVo>> getPage(ActivityReq req) {
        Page page = PageHelper.startPage(req.getPageNo(), req.getPageSize());
        List<ActivityVo> list = activityMapper.getList(req);
//        List<Activity> list = list(new LambdaQueryWrapper<Activity>()
//                .eq(Activity::getIsDeleted, BaseConstant.ZERO)
//                .eq(Objects.nonNull(req.getId()), Activity::getId, req.getId())
//                .like(StringUtil.isNotBlank(req.getName()), Activity::getName, req.getName())
//                .eq(Objects.nonNull(req.getAuditStatus()), Activity::getAuditStatus, req.getAuditStatus())
//                .orderByDesc(Activity::getCreatedAt));
//        List<ActivityVo> activityVos = new ArrayList<>();
//        if (CollectionUtils.isNotEmpty(list)) {
//            // 商家基本信息
//            Map<Long, Shop> shopMap = daoService.getShopMap(list.stream().map(Activity::getTenantId).distinct().collect(Collectors.toList()));
//            list.forEach(s -> {
//                ActivityVo activityVo = new ActivityVo();
//                BeanUtils.copyProperties(s, activityVo);
//                activityVo.setTypeDesc(ActivityEnum.getRemarkByActivity(s.getType()));
//                activityVo.setShopNickName(shopMap.get(s.getTenantId()).getShopName());
//                activityVo.setShopAvatar(shopMap.get(s.getTenantId()).getAvatar());
//                activityVos.add(activityVo);
//            });
//        }
        return PageHelpUtil.buildPage(list, page);
    }


    /**
     * 审核
     * @param activityVo
     * @return
     */
    @Override
    public BaseResp auditActivity(ActivityVo activityVo) {
        Activity activity = getById(activityVo.getId());
        if (!BaseConstant.ZERO.equals(activity.getAuditStatus())) {
            return new BaseResp(ResultCode.AUDIT_STATUS_ERROR);
        }
        activity.setAuditStatus(activityVo.getAuditStatus());
        activity.setRefuseCause(activityVo.getRefuseCause());
        updateById(activity);
        return new BaseResp();
    }

    /**
     * 查看详情
     * @param id
     * @return
     */
    @Override
    public ResultData<ActivityVo> getDetail(Long id) {
        ActivityVo vo = new ActivityVo();
        Activity activity = getById(id);
        if (Objects.isNull(activity)){
            return new ResultData<>(vo);
        }
        Shop shop = shopMapper.selectByPrimaryKey(activity.getTenantId());
        BeanUtils.copyProperties(activity, vo);
        vo.setShopNickName(shop.getShopName());
        vo.setShopAvatar(shop.getAvatar());

        // 商品信息
        List<SpuResp> respList = new ArrayList<>();
        ActivityBindSpu activityBindSpu = new ActivityBindSpu();
        activityBindSpu.setActivityId(id);
        List<ActivityBindSpu> list = bindSpuMapper.getList(activityBindSpu);
        if (CollectionUtils.isNotEmpty(list)) {
            // 处理spuIds
            List<Long> spuIds = list.stream().map(ActivityBindSpu::getSpuId).distinct().collect(Collectors.toList());
            List<Spu> spuList = spuMapper.findAllByIds(spuIds);

            spuList.forEach(s -> {
                SpuResp resp = new SpuResp();
                BeanUtils.copyProperties(s, resp);
                respList.add(resp);
            });
            // 新人专区活动价格和 活动库存
            Map<Long, ActivityBindSpu> newPriceMap = list.stream().collect(Collectors.toMap(ActivityBindSpu::getSkuId, s->s, (t1, t2) -> t1));
            List<Long> skuIds = list.stream().map(ActivityBindSpu::getSkuId).collect(Collectors.toList());
            List<Sku> skuList = skuMapper.findAllByIds(skuIds);
            List<SkuItemVO> skuItemVOList = new ArrayList<>();
            for (Sku sku : skuList) {
                SkuItemVO itemVO = new SkuItemVO();
                BeanUtils.copyProperties(sku, itemVO);
                itemVO.setNewPrice(newPriceMap.get(itemVO.getId()).getNewPrice());
                itemVO.setActivityStock(newPriceMap.get(itemVO.getId()).getActivityStock());
                skuItemVOList.add(itemVO);
            }
            Map<Long, List<SkuItemVO>> skuMap = skuItemVOList.stream().collect(Collectors.groupingBy(SkuItemVO::getSpuId));
            respList.forEach(t -> t.setSkuItemVOS(skuMap.get(t.getId())));
            vo.setSpuRespList(respList);
        }
        return new ResultData<>(vo);
    }
}
